import 'package:flutter/foundation.dart';
import '../models/auth_models.dart';
import '../services/legacy_compatibility.dart';

/// 认证状态枚举
enum AuthStatus {
  initial,
  loading,
  authenticated,
  unauthenticated,
  error,
}

/// 认证状态提供者
class AuthProvider with ChangeNotifier {
  UserInfo? _user;
  AuthStatus _status = AuthStatus.initial;
  String? _errorMessage;
  String? _verificationId;
  
  UserInfo? get user => _user;
  AuthStatus get status => _status;
  String? get errorMessage => _errorMessage;
  bool get isAuthenticated => _status == AuthStatus.authenticated && _user != null;
  bool get isLoading => _status == AuthStatus.loading;
  
  final AuthService _authService = AuthService();
  
  /// 初始化认证状态
  Future<void> initializeAuth() async {
    _setStatus(AuthStatus.loading);
    
    try {
      // 初始化认证服务
      await _authService.initialize();
      
      // 检查是否已登录
      if (_authService.isLoggedIn) {
        _user = _authService.currentUser;
        _setStatus(AuthStatus.authenticated);
      } else {
        _setStatus(AuthStatus.unauthenticated);
      }
    } catch (e) {
      _setError('初始化认证失败: $e');
    }
  }

  /// 发送验证码
  Future<bool> sendVerificationCode(String phoneNumber) async {
    _setStatus(AuthStatus.loading);
    
    try {
      _verificationId = await _authService.sendVerificationCode(phoneNumber);
      _setStatus(AuthStatus.unauthenticated);
      return true;
    } catch (e) {
      _setError('发送验证码失败: $e');
      return false;
    }
  }

  /// 验证码登录
  Future<bool> verifyCodeAndLogin(String phoneNumber, String code) async {
    if (_verificationId == null) {
      _setError('请先发送验证码');
      return false;
    }

    _setStatus(AuthStatus.loading);
    
    try {
      final loginData = await _authService.verifyCodeAndLogin(
        phoneNumber: phoneNumber,
        code: code,
        verificationId: _verificationId!,
      );
      
      _user = loginData.user;
      _setStatus(AuthStatus.authenticated);
      return true;
    } catch (e) {
      _setError('登录失败: $e');
      return false;
    }
  }

  /// 登出
  Future<void> logout() async {
    _setStatus(AuthStatus.loading);
    
    try {
      await _authService.logout();
      _user = null;
      _verificationId = null;
      _setStatus(AuthStatus.unauthenticated);
    } catch (e) {
      _setError('登出失败: $e');
    }
  }

  /// 刷新用户信息
  Future<void> refreshUserInfo() async {
    if (!isAuthenticated) return;
    
    try {
      final userInfo = await _authService.getUserInfo();
      if (userInfo != null) {
        _user = userInfo;
        notifyListeners();
      }
    } catch (e) {
      debugPrint('刷新用户信息失败: $e');
    }
  }

  /// 验证Token有效性
  Future<bool> validateToken() async {
    try {
      final isValid = await _authService.validateToken();
      if (!isValid) {
        _user = null;
        _setStatus(AuthStatus.unauthenticated);
      }
      return isValid;
    } catch (e) {
      _setError('Token验证失败: $e');
      return false;
    }
  }

  /// 设置状态
  void _setStatus(AuthStatus status) {
    _status = status;
    _errorMessage = null;
    notifyListeners();
  }

  /// 设置错误
  void _setError(String error) {
    _status = AuthStatus.error;
    _errorMessage = error;
    notifyListeners();
  }

  /// 清除错误
  void clearError() {
    _errorMessage = null;
    if (_status == AuthStatus.error) {
      _setStatus(isAuthenticated ? AuthStatus.authenticated : AuthStatus.unauthenticated);
    }
  }
}